package com.ws.wsdemo2.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @Classname RedisConfig
 * @Description TODO
 * @Date 2019/5/9 17:50
 * @Created by Administrator
 */
@Configuration
@EnableAutoConfiguration
public class RedisConfig {

    @Value("${spring.redis.host}")
    private  String host;

    @Value("${spring.redis.port}")
    private  int port;

    @Value("${spring.redis.password}")
    private  String passwd;

    @Value("${spring.redis.timeout}")
    private  int timeout;

    @Value("${spring.redis.blockWhenExhausted}")
    private  boolean blockWhenExhausted;

    @Value("${spring.redis.maxIdle}")
    private  int maxIdle;

    @Value("${spring.redis.maxWaitMillis}")
    private  int maxWaitMillis;

    @Value("${spring.redis.maxTotal}")
    private  int maxTotal;

    @Value("${spring.redis.testOnBorrow}")
    private  boolean testOnBorrow;


    private  JedisPool jedisPool;

    @Bean
    public JedisPoolConfig getRedisConfig() {
        JedisPoolConfig config=new JedisPoolConfig();
        return config;
    }

    @Bean
    public JedisPool getJedisPool() {
        JedisPoolConfig config=getRedisConfig();
        config.setMaxIdle(maxIdle);
        config.setMaxTotal(maxTotal);
        config.setBlockWhenExhausted(blockWhenExhausted);
        config.setTestOnBorrow(testOnBorrow);
        config.setMaxWaitMillis(maxWaitMillis);
        JedisPool jedisPool=new JedisPool(config,host,port,timeout,passwd);
        return jedisPool;
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(
            RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        //om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

}

